package controllers

import (
	"api/cache"
	"api/models"
	"encoding/json"
	beego "github.com/beego/beego/v2/server/web"
	"math"
	"strconv"
)

type OrderController struct {
	beego.Controller
}

func (c *OrderController) List() {
	c.Ctx.Output.Header("Access-Control-Allow-Origin", "*")
	orderNo := c.GetString("orderNo")
	page, _ := c.GetInt("page", 1)
	pageSize, _ := c.GetInt("pageSize", 5)
	offset := (page - 1) * pageSize

	var pageData models.OrderList

	//var orderList []models.Order
	//query := models.DB.Table("orders")
	//if orderNo != "" {
	//	query = query.Where("order_no like ?", "%"+orderNo+"%")
	//}
	//
	//var total int64
	//query.Debug().Count(&total)
	//
	//query.Limit(pageSize).Offset(offset).Find(&orderList)
	//
	//totalPage := int(math.Ceil(float64(total) / float64(pageSize)))
	//
	//pageData = models.OrderList{
	//	Page:      page,
	//	Size:      pageSize,
	//	List:      orderList,
	//	TotalPage: totalPage,
	//}

	listRedisKey := "list_orderNo_" + orderNo + "_page_" + strconv.Itoa(page)
	cacheList, _ := cache.Rdb.Get(cache.Ctx, listRedisKey).Result()

	if cacheList == "" {
		var orderList []models.Order
		query := models.DB.Table("orders")
		if orderNo != "" {
			query = query.Where("order_no like ?", "%"+orderNo+"%")
		}

		var total int64
		query.Count(&total)
		
		query.Limit(pageSize).Offset(offset).Find(&orderList)

		totalPage := int(math.Ceil(float64(total) / float64(pageSize)))

		jsonData := models.OrderList{
			Page:      page,
			Size:      pageSize,
			List:      orderList,
			TotalPage: totalPage,
		}
		jsonList, err := json.Marshal(&jsonData)
		if err != nil {
			c.Data["json"] = map[string]interface{}{
				"code": 500,
				"data": "json marshal error",
			}
			c.ServeJSON()
			return
		}

		cache.Rdb.Set(cache.Ctx, listRedisKey, jsonList, 0)

		pageData = models.OrderList{
			Page:      page,
			Size:      pageSize,
			List:      orderList,
			TotalPage: totalPage,
		}
	} else {

		json.Unmarshal([]byte(cacheList), &pageData)
	}

	c.Data["json"] = map[string]interface{}{
		"code": 200,
		"data": pageData,
	}
	c.ServeJSON()
	return
}

func (c *OrderController) Delete() {
	id, _ := c.GetInt("id")
	if id == 0 {
		c.Data["json"] = map[string]interface{}{
			"code": 500,
			"data": "id 为空",
		}
		c.ServeJSON()
		return
	}
	var order models.Order
	models.DB.Table("orders").Where("id = ?", id).First(&order)
	if order.ID == 0 {
		c.Data["json"] = map[string]interface{}{
			"code": 500,
			"msg":  "订单不存在",
		}
		c.ServeJSON()
		return
	}
	if order.Status == 2 {
		c.Data["json"] = map[string]interface{}{
			"code": 500,
			"msg":  "订单已完成，禁止删除",
		}
		c.ServeJSON()
		return
	}
	models.DB.Table("orders").Where("id = ?", id).Delete(&order)
	c.Data["json"] = map[string]interface{}{
		"code": 200,
		"msg":  "删除成功",
	}
	c.ServeJSON()
	return
}

func (c *OrderController) Remark() {
	id, _ := c.GetInt("id")
	if id == 0 {
		c.Data["json"] = map[string]interface{}{
			"code": 500,
			"data": "id 为空",
		}
		c.ServeJSON()
		return
	}
	remark := c.GetString("remark")
	if remark == "" {
		c.Data["json"] = map[string]interface{}{
			"code": 500,
			"msg":  "评论为空",
		}
		c.ServeJSON()
		return
	}
	var order models.Order
	models.DB.Table("orders").Where("id = ?", id).First(&order)
	if order.ID == 0 {
		c.Data["json"] = map[string]interface{}{
			"code": 500,
			"msg":  "订单不存在",
		}
		c.ServeJSON()
		return
	}

	order.Remark = remark
	models.DB.Table("orders").Where("id = ?", id).Updates(&order)

	c.Data["json"] = map[string]interface{}{
		"code": 200,
		"msg":  "success",
	}
	c.ServeJSON()
	return
}

func (c *OrderController) Detail() {
	id, _ := c.GetInt("id")
	if id == 0 {
		c.Data["json"] = map[string]interface{}{
			"code": 500,
			"data": "id 为空",
		}
		c.ServeJSON()
		return
	}

	var order models.Order

	listRedisKey := "list_order_detail_" + strconv.Itoa(id)
	cacheList, _ := cache.Rdb.Get(cache.Ctx, listRedisKey).Result()
	if cacheList == "" {
		models.DB.Table("orders").Where("id = ?", id).First(&order)

		jsonList, err := json.Marshal(&order)
		if err != nil {
			c.Data["json"] = map[string]interface{}{
				"code": 500,
				"data": "json marshal error",
			}
			c.ServeJSON()
			return
		}

		cache.Rdb.Set(cache.Ctx, listRedisKey, jsonList, 0)
	} else {
		json.Unmarshal([]byte(cacheList), &order)
	}

	c.Data["json"] = map[string]interface{}{
		"code": 200,
		"data": order,
	}
	c.ServeJSON()
	return

}
